<!-- 多选题 -->
<template>
  <div class="multiple-subject">
    <el-form ref="ruleFormRef" :model="formData">
      <el-form-item label="题目名称:" label-width="80px">
        <el-input
          placeholder="请输入题目名称"
          v-model="formData.subjectName"
        ></el-input>
      </el-form-item>

      <el-form-item
        :label="[
          item.optionType == 1
            ? 'A'
            : item.optionType == 2
            ? 'B'
            : item.optionType == 3
            ? 'C'
            : 'D',
        ]"
        v-for="(item, index) in formData.optionList"
        :key="index"
        label-width="80"
      >
        <div class="option">
          <div class="ipt">
            <el-tooltip content="请点击选项输入内容" placement="top">
              <el-input
                placeholder="请使用富文本编辑器输入选项内容"
                @focus="handlerFocus(index, $event)"
                v-model="item.optionContent"
                :disabled="index == disabledIndex"
              ></el-input>
            </el-tooltip>

            <div class="close" @click="close(index)">X</div>
          </div>
        </div>
      </el-form-item>
      <el-form-item v-if="isShowConfirmButton" label-width="80px">
        <el-tooltip content="清空当前选项内容" placement="top">
          <el-button plain round style="width: 120px" @click="cancel"
            >取消</el-button
          >
        </el-tooltip>
        <el-tooltip content="确认当前选项内容" placement="top">
          <el-button @click="confirm" type="primary" round style="width: 120px"
            >确认</el-button
          >
        </el-tooltip>
      </el-form-item>
      <el-form-item label="题目操作:" label-width="80px">
        <el-button type="text" icon="plus"> 添加选项 </el-button>
        <span style="margin: 0 10px 0 20px">正确选项</span>
        <el-select
          v-model="isCorrect"
          multiple
          placeholder="请选择正确答案"
          style="width: 240px"
          @change="handlerChangeSelect"
        >
          <el-option
            v-for="item in defaultOptions"
            :key="item.optionType"
            :label="item.label"
            :value="item.optionType"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="试题解析:" label-width="80px">
        <el-input
          v-model="formData.subjectParse"
          maxlength="500"
          type="textarea"
          placeholder="试题解析 (非必填 | 限500字)"
          style="margin-left: 10px"
        />
      </el-form-item>
      <el-form-item label="职级选择:" label-width="80px">
        <Rank :handlerLevel="handlerLevel" :level="formData.subjectDifficult" />
      </el-form-item>
    </el-form>
    <Category
      :handlerCategoryIds="handlerCategoryIds"
      :handlerLabelIds="handlerLabelIds"
      :categoryIds="formData.categoryIds"
      :labelIds="formData.labelIds"
    />
    <div
      class="handler"
      style="
        width: 100%;
        margin-top: 20px;
        display: flex;
        justify-content: center;
      "
    >
      <el-button type="info" plain round style="width: 120px">清空</el-button>
      <el-button type="primary" round style="width: 120px" @click="submit"
        >提交</el-button
      >
    </div>

    <el-dialog
      v-model="isSubmitDialogVisible"
      width="500"
      :show-close="false"
      :modal="true"
    >
      <div
        class="content"
        style="display: flex; justify-content: center; color: rgb(86, 169, 241)"
      >
        <h2 style="display: flex; align-items: center">
          <svg
            t="1711259143276"
            class="icon"
            viewBox="0 0 1055 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="8952"
            width="45"
            height="45"
          >
            <path
              d="M573.213047 261.967704s125.388395 185.46511 206.373624 190.700075c0 0 23.510324-133.22517 2.617483-193.301884-0.015674-0.015674-99.276262-28.74529-208.991107 2.601809zM264.961352 460.504554l86.204521 23.510324 52.23994-91.423814c0.015674-0.015674-135.826979 47.004975-138.444461 67.91349zM562.75879 679.934245l15.673549 86.204521 23.510324-20.908515 39.183873-70.530972 2.617483-47.020648zM406.023296 538.8723l-86.204521 33.964582 13.056066 23.510324-39.183873 104.495553 5.219292 18.291032 20.892841-7.836774 62.694197 15.673549s57.474905 15.673549 83.587039-10.454257l33.964582-41.801356 5.219292-28.729616-99.244915-107.113037z"
              fill="#C0EAFF"
              p-id="8953"
            ></path>
            <path
              d="M558.840402 472.259716m-82.286134 0a82.286134 82.286134 0 1 0 164.572268 0 82.286134 82.286134 0 1 0-164.572268 0Z"
              fill="#C0EAFF"
              p-id="8954"
            ></path>
            <path
              d="M553.480048 698.961933a15.673549 15.673549 0 0 1-11.081199-4.592349L343.093995 495.049056a15.673549 15.673549 0 0 1-3.322792-17.256577c32.444247-75.703243 140.403655-181.734805 211.624263-222.439013 21.378721-12.209695 51.26818-19.999449 88.837678-23.165506a15.689223 15.689223 0 0 1 2.633156 31.253058c-32.992821 2.774218-58.540707 9.216047-75.922673 19.137403-62.223991 35.563283-160.058286 131.030873-193.928826 198.082317l183.772366 183.78804c67.051444-33.886214 162.534707-131.720509 198.082317-193.9445 30.720157-53.775948 19.372507-166.970321 14.811504-202.768708a736.609799 736.609799 0 0 0-64.12049-5.376027 15.673549 15.673549 0 0 1-15.046608-16.269145 15.375752 15.375752 0 0 1 16.269145-15.046607c36.284267 1.410619 66.111031 5.407375 76.063735 6.865015a14.184562 14.184562 0 0 1 5.172271 0.689636c3.13471 1.003107 5.877581 2.86826 7.852448 5.329007a15.124975 15.124975 0 0 1 2.946627 5.313333c0.595595 1.880826 0.846372 3.824346 0.752331 5.736519 3.84002 26.284542 21.378721 163.020587-17.507355 231.059464-40.704208 71.220608-146.735769 179.19569-222.439012 211.639937a15.266037 15.266037 0 0 1-6.144032 1.285231z"
              fill="#1296db"
              p-id="8955"
              data-spm-anchor-id="a313x.search_index.0.i7.58d83a81BlVvzu"
              class="selected"
            ></path>
            <path
              d="M354.190868 499.641406a15.673549 15.673549 0 0 1-3.683284-0.438859l-89.99752-21.660845a15.673549 15.673549 0 0 1-7.962163-25.751642c67.317894-74.402339 153.36568-73.383558 156.954923-73.493273a15.673549 15.673549 0 0 1 15.344405 16.002694 15.783264 15.783264 0 0 1-15.94 15.344405c-0.799351-0.015674-59.700549-0.329145-113.241394 44.121041l62.17697 14.96824a15.657876 15.657876 0 0 1-3.651937 30.908239zM579.168996 792.987556a15.642202 15.642202 0 0 1-15.23469-12.005939l-21.660845-89.99752a15.673549 15.673549 0 1 1 30.46938-7.335221l14.968239 62.17697c44.387492-53.462477 44.136715-112.583105 44.121042-113.241394a15.673549 15.673549 0 0 1 15.407099-15.908653h0.282123a15.673549 15.673549 0 0 1 15.67355 15.328732c0.062694 3.62059 0.956087 89.590008-73.493273 156.954923a15.845958 15.845958 0 0 1-10.532625 4.028102zM770.825157 481.303354a15.673549 15.673549 0 0 1-8.495063-2.507768c-133.287864-86.047786-198.975709-197.267292-201.718581-201.969357a15.689223 15.689223 0 0 1 27.083894-15.783264c0.642616 1.081475 64.951189 109.620804 191.640488 191.405384a15.689223 15.689223 0 0 1-8.510738 28.855005zM559.169547 574.451257a100.201001 100.201001 0 0 1-71.079547-29.387905 100.63986 100.63986 0 0 1 0-142.174766 15.657876 15.657876 0 1 1 22.162399 22.162399 69.277088 69.277088 0 0 0 0 97.849969 69.261415 69.261415 0 0 0 97.834295 0 69.277088 69.277088 0 0 0 0-97.849969 69.230068 69.230068 0 0 0-42.83581-19.999449 15.673549 15.673549 0 0 1 2.727198-31.22171 100.624187 100.624187 0 0 1 62.271011 29.05876 100.63986 100.63986 0 0 1 0 142.174766 100.201001 100.201001 0 0 1-71.079546 29.387905z"
              fill="#1296db"
              p-id="8956"
              data-spm-anchor-id="a313x.search_index.0.i8.58d83a81BlVvzu"
              class="selected"
            ></path>
            <path
              d="M459.611161 738.725728a15.673549 15.673549 0 0 1-7.382241-29.49762c20.077817-10.720708 33.933234-32.914454 41.174414-65.969969a15.673549 15.673549 0 0 1 30.626115 6.708279c-9.310088 42.443972-28.494513 71.690815-57.05172 86.925505a15.595182 15.595182 0 0 1-7.366568 1.833805zM384.503513 744.070409a15.595182 15.595182 0 0 1-3.871367-0.485881c-18.291032-4.655044-31.002281-11.049852-31.535181-11.316302a16.457227 16.457227 0 0 1-2.194297-1.347925c-9.059312-6.645585-32.162123 1.959194-44.904719 9.858662a15.673549 15.673549 0 1 1-23.949183-13.588967c1.253884-68.900923 22.930403-110.420155 38.886076-131.783203a71.283302 71.283302 0 0 1-11.128221-10.140787 15.673549 15.673549 0 0 1 0.454533-21.143618c44.136715-46.221297 102.222889-34.434788 104.667963-33.91756 8.463717 1.818132 13.855418 10.140786 12.052959 18.620176a15.736244 15.736244 0 0 1-18.526135 12.068633c-1.520334-0.313471-32.63233-6.26942-61.518681 13.056067l0.391839 0.015673a15.673549 15.673549 0 0 1 9.560865 28.102674c-1.441967 1.159843-34.199685 28.243736-41.926745 100.138307 16.128082-5.485742 36.832841-8.526411 53.196027 2.539115 2.774218 1.300905 11.958918 5.360354 24.215633 8.47939a15.673549 15.673549 0 0 1 11.331977 19.059036 15.736244 15.736244 0 0 1-15.203343 11.78651z"
              fill="#1296db"
              p-id="8957"
              data-spm-anchor-id="a313x.search_index.0.i9.58d83a81BlVvzu"
              class="selected"
            ></path>
            <path
              d="M360.303553 683.836958a15.689223 15.689223 0 0 1-13.02472-24.372369c3.260098-4.890147 8.040531-10.203481 13.839744-15.407099a15.657876 15.657876 0 1 1 20.939862 23.322242c-5.140924 4.608024-7.664366 7.915142-8.69882 9.482497a15.673549 15.673549 0 0 1-13.056066 6.974729zM409.612539 648.806576a15.673549 15.673549 0 0 1-4.513982-30.68881c9.999724-3.009321 19.043362-3.463854 26.84879-1.332252 2.366706-1.598702 9.090659-14.560727 11.958918-25.579232a15.673549 15.673549 0 0 1 30.328318 7.915142c-1.473314 5.642478-9.748948 34.35642-27.867571 44.842025a29.168475 29.168475 0 0 1-22.663952 3.072015c-0.70531-0.203756-3.542222-0.70531-9.576539 1.112822a15.971347 15.971347 0 0 1-4.513982 0.65829z"
              fill="#1F87DD"
              p-id="8958"
            ></path>
          </svg>
          录入成功！贡献榜活力值 + 1
        </h2>
      </div>
      <div class="btn" style="display: flex; justify-content: center">
        <el-button style="width: 100px" round @click="$router.push('/subject')"
          >返回首页</el-button
        >
        <el-button
          round
          type="primary"
          style="width: 100px"
          @click="refreshFormData"
          >在录一题</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
  
<script setup>
import { ref, onMounted } from "vue";
import { AiEditor } from "aieditor";
import "aieditor/dist/style.css";
import { ElMessage } from "element-plus";
import Rank from "./Components/Rank.vue";
import Category from "./Components/Category.vue";
import { useRouter, useRoute } from "vue-router";
import {
  reqAddSubject,
  querySubjectInfo,
  updateSubjectInfo,
} from "@/api/subject/subject";

let $router = useRouter();
let $route = useRoute();

// 富文本框
let aiEditor = null;

// 是否展示输入框区域的确认按钮
let isShowConfirmButton = ref(false);

// 是否提交  提交后显示弹出框
let isSubmitDialogVisible = ref(false);

// 表单实例
let ruleFormRef = ref();

// 正确答案
let isCorrect = ref([]);

// 表单数据
let formData = ref({
  subjectType: 2, // 题目类型
  subjectName: "", // 题目名称
  subjectParse: "", // 试题解析
  subjectDifficult: "", // 题目难度
  subjectScore: "2", // 题目分数
  categoryIds: [], // 二级分类Id
  labelIds: [], // 三级标签Id
  optionList: [
    {
      optionType: 1, // 选项 ABCD
      optionContent: "", // 选项答案
      isCorrect: 0, // 是否正确
    },
    {
      optionType: 2, // 选项 ABCD
      optionContent: "", // 选项答案
      isCorrect: 0, // 是否正确
    },
    {
      optionType: 3, // 选项 ABCD
      optionContent: "", // 选项答案
      isCorrect: 0, // 是否正确
    },
    {
      optionType: 4, // 选项 ABCD
      optionContent: "", // 选项答案
      isCorrect: 0, // 是否正确
    },
  ],
});
// 移除选项时，遍历该数据重新调整顺序
const defaultOptions = ref([
  {
    optionType: 1,
    label: "A",
  },
  {
    optionType: 2,
    label: "B",
  },
  {
    optionType: 3,
    label: "C",
  },
  {
    optionType: 4,
    label: "D",
  },
]);

// 用于存放用户点击时的输入框下标
let tempIndex = null;
// 用于禁用用户点击时的输入框  防止用户直接在输入框输入
let disabledIndex = ref(null);

// 输入框聚焦时触发
const handlerFocus = (index, e) => {
  // 先清空上次点击的下标，因为这个下标存储答案时需要使用到
  tempIndex = null;
  // 展示确认按钮
  isShowConfirmButton.value = true;
  /**
   * 用户如果点击了A输入框，但是没有输入值是不能输入B的，点击其他输入框也同理
   */
  // if (aiEditor != null) {
  //   if (aiEditor.isEmpty()) {
  //     // console.log("点击了，但是没有值");
  //     ElMessage.info("请先输入正在编辑的选项内容");
  //     return;
  //   }
  // else {
  //   // console.log("点击了，有值");

  //   // 富文本的值
  //   const optionAnswer = aiEditor.getHtml();
  //   // 收集富文本的值
  //   formData.value.optionList[tempIndex].optionContent = optionAnswer;
  //   tempIndex = null;
  // }
  // }

  if (tempIndex == null) {
    // 保存当前用户点击的输入框下标，用于保存用户输入的值
    tempIndex = index;
  }
  // 将用户当前点击的输入框设置为禁用状态
  disabledIndex.value = index;

  let that = e.target; // 当前点击的元素
  /**
   * 根据当前的节点找到父节点，在父节点下插入一个新的节点，该节点用于放置富文本框
   * 业务逻辑：1.当前逻辑只有在页面已经存在富文本框这个节点，那么才会走到这里
   *          2.防止上面逻辑错误，也要查询页面是否已经有这个富文本的节点，如果有需要先删除当前节点，页面只展示一个富文本框
   *          3.没有富文本这个节点，那么生成节点并初始化节点
   */
  let parentNode = that.parentElement.parentElement.parentElement.parentElement;
  let current = document.querySelector(".option .current");
  if (current) {
    document.querySelector(".option .current").remove();
  }
  let childNode = document.createElement("div");
  newAiEditor(childNode);
  childNode.classList.add("current");
  /**
   * 初始化节点数据
   */
  childNode.style.width = "100%";
  childNode.style.height = "300px";
  childNode.style.marginTop = "15px";
  childNode.style.background = "pink";

  parentNode.appendChild(childNode);
};

// 新建富文本编辑器
const newAiEditor = (childNode) => {
  // 富文本编辑器
  aiEditor = new AiEditor({
    element: childNode,
    placeholder: "点击输入内容...",
    content: "",
    contentRetentionKey: true, // 自动保存（缓存）到 localStorage 的 key 值，默认为：ai-editor-content。
  });
};

// 移除选项
const close = (index) => {
  // 禁用框重置为null，不然如果有下标，那么这个下标的输入框永远为禁用状态
  disabledIndex.value = null;
  // 当前输入框的下标也需要重置为null，不然点击到其他的输入框时也会让其他输入框置为禁用状态
  tempIndex = null;
  // 移除时需要判断当前页面是否有复选框的存在，如果有则需要一并移除
  let current = document.querySelector(".option .current");
  if (current) {
    document.querySelector(".option .current").remove();
    aiEditor = null;
  }
  // 删除当前的选项框
  formData.value.optionList.splice(index, 1);
  // 拿到当前选项框的长度，循环遍历换取新数据
  let len = formData.value.optionList.length;
  for (let i = 0; i < len; i++) {
    formData.value.optionList[i] = defaultOptions.value[i];
  }
};

// 输入框区域的确认按钮，点击后隐藏按钮并且移除已展示的富文本区，同时保存富文本内容到相应的输入框中
const confirm = () => {
  if (aiEditor.isEmpty()) {
    ElMessage.info("请先输入正在编辑的选项内容");
    return;
  }
  isShowConfirmButton.value = false;
  const optionAnswer = aiEditor.getHtml();
  formData.value.optionList[tempIndex].optionContent = optionAnswer;
  document.querySelector(".option .current").remove();
  disabledIndex.value = 999;
  aiEditor = null;
  tempIndex = null;
};

// 输入框区域的取消按钮，点击后隐藏按钮并且移除已展示的富文本区域
const cancel = () => {
  aiEditor = null;
  document.querySelector(".option .current").remove();
  isShowConfirmButton.value = false;
  disabledIndex.value = 999;
};

// 选择正确答案时触发,将相应的选项正确答案置为1
const handlerChangeSelect = (val) => {
  formData.value.optionList.forEach((op) => {
    op.isCorrect = 0;
  });

  val.forEach((correct) => {
    formData.value.optionList.forEach((item) => {
      if (item.optionType == correct) {
        item.isCorrect = 1;
      }
    });
  });
};

// 收集分类组件的二级分类Id
const handlerCategoryIds = (categoryId) => {
  formData.value.categoryIds = categoryId;
};

// 收集分类组件的三级标签Id
const handlerLabelIds = (labelId) => {
  formData.value.labelIds = labelId;
};

// 收集职级
const handlerLevel = (level) => {
  formData.value.subjectDifficult = level;
};

// 提交
const submit = () => {
  if (!formData.value.subjectName) {
    return;
  }
  if ($route.query.id) {
    // 更新操作
    formData.value.id = $route.query.id;
    updateSubjectInfo(formData.value).then((res) => {
      if (res.code == 200) {
        ElMessage.success("修改成功");
        $router.go(-1);
      } else {
        ElMessage.error("修改失败");
      }
    });
  } else {
    // 新增操作
    reqAddSubject(formData.value).then((res) => {
      if (res.code == 200) {
        isSubmitDialogVisible.value = true;
      } else {
        ElMessage.error("提交失败");
        refreshFormData();
      }
    });
  }
};

const refreshFormData = () => {
  formData.value = {
    subjectType: 1, // 题目类型
    subjectName: "", // 题目名称
    subjectParse: "", // 试题解析
    subjectDifficult: "", // 题目难度
    subjectScore: "2", // 题目分数
    categoryIds: [], // 二级分类Id
    labelIds: [], // 三级标签Id
    optionList: [
      {
        optionType: 1, // 选项 ABCD
        optionContent: "", // 选项答案
        isCorrect: 0, // 是否正确
      },
      {
        optionType: 2, // 选项 ABCD
        optionContent: "", // 选项答案
        isCorrect: 0, // 是否正确
      },
      {
        optionType: 3, // 选项 ABCD
        optionContent: "", // 选项答案
        isCorrect: 0, // 是否正确
      },
      {
        optionType: 4, // 选项 ABCD
        optionContent: "", // 选项答案
        isCorrect: 0, // 是否正确
      },
    ],
  };
  isCorrect.value = [];
  isSubmitDialogVisible.value = false;
};

onMounted(() => {
  const id = $route.query.id;
  if (id) {
    /**
     * 当前为更新操作
     * 获取题目信息
     */
    const data = {
      id,
    };
    getSubjectInfo(data);
  }
});

// 获取题目信息
const getSubjectInfo = (data) => {
  querySubjectInfo(data).then((res) => {
    if (res.code == 200) {
      formData.value.subjectName = res.data.subjectName;
      formData.value.subjectParse = res.data.subjectParse;
      formData.value.subjectType = res.data.subjectType;
      formData.value.subjectScore = res.data.subjectScore;
      formData.value.subjectDifficult = String(res.data.subjectDifficult);
      formData.value.categoryIds = res.data.categoryIds;
      formData.value.labelIds = res.data.labelIds;
      res.data.optionList.forEach((op, index) => {
        formData.value.optionList[index] = op;
        if (op.isCorrect) {
          isCorrect.value.push(op.optionType);
        }
      });
    } else {
      ElMessage.error("题目详情失败,请稍后重试");
      $router.go(-1);
    }
  });
};
</script>
  
<style scoped lang="scss">
.multiple-subject {
  width: 100%;
  .option {
    width: 100%;

    .ipt {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .current {
        width: 100%;
        height: 300px;
      }
      .close {
        width: 20px;
        background-color: #3b3b3b;
        height: 20px;
        border-radius: 50%;
        margin: 0 15px;
        font-size: 10px;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.5s;
      }
    }
  }
}
</style>